<template>
  <div class="login-container">
    <div class="login-box">
      <img src="../assets/logo.png"
           alt="">
      <el-form ref="form"
               :rules="rules"
               :model="form">
        <el-form-item prop="username">
          <el-input v-model="form.username"
                    hide-required-asterisk=false
                    prefix-icon="el-icon-user-solid"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password"
                    v-model="form.password"
                    prefix-icon="el-icon-lock"></el-input>
        </el-form-item>
        <el-form-item class="login-btn">
          <el-button type="primary"
                     @click="submitForm('form')">登录</el-button>
          <el-button type="info"
                     @click="resetForm('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { loginApi } from '../api'
export default {
  data () {
    return {
      form: {
        username: 'admin',
        password: '123456',
        delivery: false
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { message: '请输入正确的用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { max: 14, min: 3, message: '长度在 3 到 14 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 二次满足就进入
          // 使用async await async必须写在最近的函数 await后面必须接一个promins对象
          const res = await loginApi(this.form)
          if (res.data.meta.status === 200) {
            // 必须先存后再跳转
            localStorage.setItem('token', res.data.data.token)
            this.$router.push('Home')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped lang='less'>
.login-container {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: #2b4b6b;
}
.login-box {
  width: 450px;
  height: 304px;
  background-color: #fff;
  position: absolute;
  margin: auto;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  box-shadow: 0 0 10px 0px #fff;
  border-radius: 1%;
}
.el-form {
  padding: 110px 20px;
}
.login-btn {
  text-align: right;
}
img {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  transform: translateY(-50%);
  margin: auto;
  width: 130px;
  height: 130px;
  border-radius: 50%;
  border: 10px solid #fff;
  background-color: #efefef;
  box-shadow: 0 0 10px 0px #ddd;
}
</style>
